<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="820px"
      draggable
      destroy-on-close
      align-center
      @close="closeDialog"
      class="printDialog"
      style="min-width: 820px"
    >
      <div>
        <div id="printBox" v-loading="loading">
          <!-- 循环生成第几页 page-break为打印分页标识-->
          <!-- <div
          v-for="(pageItem, pageIndex) in printDataList"
          :key="pageItem?.id"
          class="page-break"
        > -->
          <div
            style="padding: 20px 0; margin: 0 10px; position: relative"
            id="table"
          >
            <img
              src="@/assets/images/dlcx.png"
              width="150"
              style="position: absolute; left: 20px; top: 5px"
            />
            <div
              style="
                font-size: 22px;
                display: flex;
                justify-content: center;
                margin-bottom: 10px;
              "
            >
              纠正/预防措施要求表
            </div>

            <!-- 送货单基本信息 -->
            <div
              style="
                display: flex;
                margin-bottom: 2px;
                font-size: 14px;
                font-weight: 400;
              "
            >
              <div style="flex: 1"></div>
              <div style="flex: 1">
                <div style="text-align: right">
                  编号: {{ printData?.qualityProblemCode || "" }}
                </div>
              </div>
            </div>
            <table
              border="1"
              cellpadding="0"
              cellspacing="0"
              align="center"
              class="dashed-border"
            >
              <colgroup>
                <col width="120" />
                <col width="120" />
                <col width="120" />
                <col width="120" />
                <col width="120" />
                <col width="120" />
              </colgroup>
              <tr>
                <td colspan="4">
                  责任部门/责任人：{{ printData?.departmentName || "" }}
                  <span
                    v-show="
                      printData?.departmentName &&
                      printData?.departmentManagerName
                    "
                    >/</span
                  >{{ printData?.departmentManagerName || "" }}
                </td>
                <td colspan="2">
                  编号：{{ printData?.qualityProblemCode || "" }}
                </td>
              </tr>
              <tr>
                <td colspan="1">整改期限</td>
                <td colspan="5">
                  限
                  {{
                    formatDate(printData?.provisionalMeasuresDeadline)
                  }}前上报纠正预防措施; 限{{
                    formatDate(printData?.rectificationDeadline)
                  }}前整改完毕。
                </td>
              </tr>
              <tr>
                <td colspan="6">
                  <div style="min-height: 80px">
                    <div style="margin-bottom: 15px">
                      存在(或潜在)问题及整改要求:
                    </div>
                    <div>{{ printData?.describe || "" }}</div>
                    <div style="margin: 5px 0">
                      {{ printData?.rectificationRequirement || "" }}
                    </div>
                  </div>
                </td>
              </tr>
              <tr>
                <td colspan="3">
                  <div style="margin-bottom: 35px">
                    提出部门:{{ printData?.proposeDepartmentName || "" }}
                  </div>
                  <div style="display: flex">
                    <div style="flex: 1">
                      提出人：{{ printData?.createdUserName || "" }}
                    </div>
                    <div style="flex: 1">
                      <div style="text-align: right">
                        {{ formatDate(printData?.provisionalMeasuresDeadline) }}
                      </div>
                    </div>
                  </div>
                </td>
                <td colspan="3">
                  <div style="margin-bottom: 35px">提出部门（盖章）：</div>
                  <div style="display: flex">
                    <div style="flex: 1">经理（签字）：</div>
                    <div style="flex: 1">
                      <div style="text-align: right">
                        <span style="margin-right: 30px">年</span>
                        <span style="margin-right: 30px">月</span>
                        <span>日</span>
                      </div>
                    </div>
                  </div>
                </td>
              </tr>

              <tr
                v-for="(item, index) in printData?.workOrderList"
                :key="index"
              >
                <!-- 只有总结 -->
                <td
                  colspan="6"
                  v-if="templateType(item.exceptionBusinessType) === 1"
                >
                  <div style="margin-bottom: 15px; font-weight: 600">
                    {{
                      dictionaryStore.filterDictName(
                        "problemTicket",
                        item.exceptionBusinessType
                      )
                    }}:
                  </div>
                  <div
                    v-for="(workItem, workIndex) in item.listWork"
                    :key="workIndex"
                    style="line-height: 20px"
                  >
                    <div style="margin: 10px 0">
                      {{ workItem?.exceptionContent || "" }}
                    </div>

                    <div
                      style="display: flex"
                      v-if="item.exceptionBusinessType === 21"
                    >
                      <div style="flex: 1"></div>
                      <div style="flex: 1">
                        <div style="text-align: right">
                          完成时间：{{ formatDate(workItem?.planDate) }}
                        </div>
                      </div>
                    </div>
                  </div>
                </td>

                <!-- 只有时间 -->
                <td
                  colspan="6"
                  v-if="templateType(item.exceptionBusinessType) === 5"
                >
                  <div style="margin-bottom: 15px; font-weight: 600">
                    {{
                      dictionaryStore.filterDictName(
                        "problemTicket",
                        item.exceptionBusinessType
                      )
                    }}:
                  </div>
                  <div
                    v-for="(workItem, workIndex) in item.listWork"
                    :key="workIndex"
                    style="line-height: 20px"
                  >
                    <div style="margin: 10px 0">
                      {{
                        workItem?.exceptionContent
                          ? formatDate(workItem?.exceptionContent)
                          : ""
                      }}
                    </div>
                  </div>
                </td>

                <!-- 原因分析、确认根本原因 -->
                <td
                  colspan="6"
                  v-if="templateType(item.exceptionBusinessType) === 2"
                >
                  <div style="margin-bottom: 15px; font-weight: 600">
                    {{
                      dictionaryStore.filterDictName(
                        "problemTicket",
                        item.exceptionBusinessType
                      )
                    }}:
                  </div>
                  <div
                    v-for="(workItem, workIndex) in item.listWork"
                    :key="workIndex"
                    style="line-height: 20px"
                  >
                    <!-- 原因分析 -->
                    <div style="margin-bottom: 15px">
                      <div style="margin-bottom: 8px">原因分析</div>
                      <div
                        v-for="(self, selfIndex) in workItem?.details"
                        :key="selfIndex"
                        style="margin-bottom: 3px; text-indent: 20px"
                      >
                        <div>
                          {{ selfIndex + 1 }}、{{
                            self?.exceptionContent || ""
                          }}
                        </div>
                      </div>
                    </div>
                    <!-- 确认根本原因 -->
                    <div style="margin-bottom: 10px">
                      <div style="margin-bottom: 8px">确认根本原因</div>
                      <div>
                        {{ workItem?.exceptionContent || "" }}
                      </div>
                    </div>
                  </div>
                </td>

                <!-- 有总结、时间、负责人 -->
                <td
                  colspan="6"
                  v-if="templateType(item.exceptionBusinessType) === 3"
                >
                  <div style="margin-bottom: 15px; font-weight: 600">
                    {{
                      dictionaryStore.filterDictName(
                        "problemTicket",
                        item.exceptionBusinessType
                      )
                    }}:
                  </div>
                  <div
                    v-for="(workItem, workIndex) in item.listWork"
                    :key="workIndex"
                    style="line-height: 20px"
                  >
                    <div style="margin: 10px 0">
                      {{ workItem?.exceptionContent || "" }}
                    </div>

                    <div style="display: flex">
                      <div style="flex: 1">
                        负责人：{{ workItem?.superintendent }}
                      </div>
                      <div style="flex: 1">
                        <div style="text-align: right">
                          完成时间：{{ formatDate(workItem?.planDate) }}
                        </div>
                      </div>
                    </div>
                  </div>
                </td>

                <!-- 有总结、时间、负责人、验证信息 -->
                <td
                  colspan="6"
                  v-if="templateType(item.exceptionBusinessType) === 4"
                >
                  <div style="margin-bottom: 15px; font-weight: 600">
                    {{
                      dictionaryStore.filterDictName(
                        "problemTicket",
                        item.exceptionBusinessType
                      )
                    }}:
                  </div>
                  <div
                    v-for="(workItem, workIndex) in item.listWork"
                    :key="workIndex"
                    style="line-height: 20px"
                  >
                    <!-- <div style="margin: 15px 0">
                      {{
                        item.exceptionBusinessType === 14
                          ? workItem?.d51?.exceptionContent || ""
                          : workItem?.d52?.exceptionContent || ""
                      }}
                    </div> -->

                    <div style="margin: 10px 0">
                      <div style="margin-bottom: 8px">验证结果：</div>
                      {{ workItem?.exceptionContent || "" }}
                    </div>

                    <!-- <div style="display: flex">
                      <div style="flex: 1">
                        负责人：{{
                          item.exceptionBusinessType === 14
                            ? workItem?.d51?.superintendent || ""
                            : workItem?.d52?.superintendent || ""
                        }}
                      </div>
                      <div style="flex: 1">
                        <div style="text-align: right">
                          完成时间：{{
                            item.exceptionBusinessType === 14
                              ? formatDate(workItem?.d51?.planDate)
                              : formatDate(workItem?.d52?.planDate)
                          }}
                        </div>
                      </div>
                    </div> -->
                  </div>
                </td>

                <!-- 团队成员 -->
                <td
                  colspan="6"
                  v-if="item.exceptionBusinessType === 2"
                  style="padding-bottom: 10px"
                >
                  <div style="margin-bottom: 15px; font-weight: 600">
                    {{
                      dictionaryStore.filterDictName(
                        "problemTicket",
                        item.exceptionBusinessType
                      )
                    }}:
                  </div>
                  <div
                    v-for="(workItem, workIndex) in item.listWork"
                    :key="workIndex"
                    style="line-height: 20px"
                  >
                    <div style="display: flex">
                      <div style="flex: 1; max-width: 40px; padding: 2px 3px">
                        {{ workIndex + 1 }}
                      </div>
                      <div style="flex: 1; padding: 2px 3px; max-width: 120px">
                        {{ workItem?.teamUserName || "" }}
                      </div>
                      <div style="flex: 1; padding: 2px 3px; max-width: 110px">
                        {{
                          workItem?.isLeader == 1 ? "小组负责人" : "非负责人"
                        }}
                      </div>
                      <div style="flex: 1; padding: 2px 3px">
                        {{ workItem?.departmentName || "" }}
                      </div>
                      <div style="flex: 1; padding: 2px 3px; max-width: 100px">
                        {{ workItem?.roleName || "" }}
                      </div>
                      <div style="flex: 1; padding: 2px 3px; max-width: 120px">
                        {{ workItem?.telNumber || "19566666666" }}
                      </div>
                    </div>
                  </div>
                </td>

                <!-- 问题描述 -->
                <td colspan="6" v-if="item.exceptionBusinessType === 3">
                  <div style="margin-bottom: 15px; font-weight: 600">
                    {{
                      dictionaryStore.filterDictName(
                        "problemTicket",
                        item.exceptionBusinessType
                      )
                    }}:
                  </div>
                  <div
                    v-for="(workItem, workIndex) in item.listWork"
                    :key="workIndex"
                    style="line-height: 20px"
                  >
                    <div
                      v-for="(problem, problemIndex) in q8dd2Object"
                      :key="problemIndex"
                      style="margin-bottom: 15px"
                    >
                      <div style="margin-bottom: 5px">
                        {{ problemIndex + 1 }}、{{ problem?.title || "" }}
                      </div>
                      <div style="text-indent: 20px">
                        <!-- <div> -->
                        {{ workItem[problem.keyWord] ?? "" }}
                      </div>
                    </div>
                  </div>
                </td>

                <!-- 开始时间、完成时间、复杂表格 -->
                <td colspan="6" v-if="item.exceptionBusinessType === 6">
                  <div style="margin-bottom: 15px; font-weight: 600">
                    {{
                      dictionaryStore.filterDictName(
                        "problemTicket",
                        item.exceptionBusinessType
                      )
                    }}:
                  </div>
                  <table
                    border="1"
                    cellpadding="0"
                    cellspacing="0"
                    align="center"
                    class="dashed-border"
                    style="width: 100%"
                  >
                    <thead>
                      <tr>
                        <th rowspan="2"></th>
                        <th rowspan="2" align="left">地点</th>
                        <th rowspan="2" align="left">零件号</th>
                        <th rowspan="2" align="right">数量</th>
                        <th rowspan="2" align="right">问题件数量</th>
                        <th rowspan="2" align="right">不良率</th>
                      </tr>
                    </thead>
                    <tbody align="center">
                      <template
                        v-for="(tableItem, tableIndex) in item.listWork"
                        :key="tableIndex"
                      >
                        <tr>
                          <td
                            v-if="isFirstInGroup(tableIndex, item?.listWork)"
                            :rowspan="getRowspan(tableIndex, item?.listWork)"
                          >
                            {{
                              dictionaryStore.filterDictName(
                                "ImProcessType",
                                tableItem?.implementationProcessType
                              )
                            }}
                          </td>
                          <td align="left">
                            {{
                              dictionaryStore.filterDictName(
                                "ImProcessSubType",
                                tableItem?.implementationProcessSubType
                              )
                            }}
                          </td>
                          <td align="left">
                            {{ tableItem?.materialCode || "" }}
                          </td>
                          <td align="right">
                            {{ tableItem?.totalQuantity || "" }}
                          </td>
                          <td align="right">
                            {{ tableItem?.exceptionQuantity || "" }}
                          </td>
                          <td align="right">
                            {{ calculateDefectRate(tableItem) }}%
                          </td>
                        </tr>
                      </template>
                    </tbody>
                  </table>

                  <div style="display: flex; margin: 15px 0 0">
                    <div style="flex: 1">
                      开始执行时间：{{ formatDate(item?.startTime) }}
                    </div>
                    <div style="flex: 1">
                      <div style="text-align: right">
                        完成时间：{{ formatDate(item?.lastUpdateTime) }}
                      </div>
                    </div>
                  </div>
                </td>

                <!-- 表格、图号 -->
                <td
                  colspan="6"
                  v-if="item.exceptionBusinessType === 18"
                  style="padding-bottom: 10px"
                >
                  <div style="margin-bottom: 15px; font-weight: 600">
                    {{
                      dictionaryStore.filterDictName(
                        "problemTicket",
                        item.exceptionBusinessType
                      )
                    }}:
                  </div>
                  <div
                    v-for="(workItem, workIndex) in item.listWork"
                    :key="workIndex"
                    style="line-height: 20px; margin-bottom: 15px"
                  >
                    <div>
                      <div style="margin-bottom: 5px">
                        {{ workIndex + 1 }}、图号：{{
                          workItem?.figureNumber || ""
                        }}
                      </div>
                      <div style="text-indent: 20px">
                        改进：{{ workItem?.exceptionContent || "" }}
                      </div>
                    </div>
                  </div>
                </td>

                <!-- 复杂表格（项目、内容、得分、满分标准）评价意见 -->
                <td colspan="6" v-if="item.exceptionBusinessType === 19">
                  <div style="margin-bottom: 15px; font-weight: 600">
                    {{
                      dictionaryStore.filterDictName(
                        "problemTicket",
                        item.exceptionBusinessType
                      )
                    }}:
                  </div>
                  <div
                    v-for="(workItem, workIndex) in item.listWork"
                    :key="workIndex"
                    style="line-height: 20px"
                  >
                    <table
                      border="1"
                      cellpadding="0"
                      cellspacing="0"
                      align="center"
                      class="dashed-border"
                      style="width: 100%"
                    >
                      <thead>
                        <tr>
                          <th rowspan="2">项目</th>
                          <th rowspan="2">内容</th>
                          <th rowspan="2" align="right" style="width: 100px">
                            得分
                          </th>
                          <th rowspan="2" align="right">满分标准</th>
                        </tr>
                      </thead>
                      <tbody align="center">
                        <template
                          v-for="(tableItem, tableIndex) in workItem.table"
                          :key="tableIndex"
                        >
                          <tr>
                            <td
                              v-if="
                                isFirstInGroupD8(tableIndex, workItem.table)
                              "
                              :rowspan="
                                getRowspanD8(tableIndex, workItem.table)
                              "
                            >
                              {{
                                dictionaryStore.filterDictName(
                                  "ProblemSummary",
                                  tableItem.problemSummary
                                )
                              }}
                            </td>
                            <td align="left">
                              {{ tableItem?.subProblemSummary || "" }}
                            </td>
                            <td align="right">
                              {{ tableItem?.ownPoint || "" }}
                            </td>
                            <td align="right">
                              {{ tableItem?.fullPoint || "" }}
                            </td>
                          </tr>
                        </template>
                        <tr>
                          <td colspan="2" align="center">合计</td>
                          <td align="right">
                            {{ getGrossScoreD8(workItem.table) }}
                          </td>
                          <td align="right">
                            {{
                              workItem.table.reduce(
                                (accumulator: any, currentValue: any) =>
                                  accumulator + currentValue.fullPoint,
                                0
                              )
                            }}
                          </td>
                        </tr>
                      </tbody>
                    </table>

                    <div style="margin: 20px 0 10px">
                      <div style="margin-bottom: 5px">评价意见：</div>
                      <div style="">
                        {{ workItem?.exceptionContent || "" }}
                      </div>
                    </div>
                  </div>
                </td>

                <!-- 23 -->
                <td colspan="6" v-if="item.exceptionBusinessType === 23">
                  <div style="margin-bottom: 15px; font-weight: 600">
                    {{
                      dictionaryStore.filterDictName(
                        "problemTicket",
                        item.exceptionBusinessType
                      )
                    }}:
                  </div>
                  <div
                    v-for="(workItem, workIndex) in item.listWork"
                    :key="workIndex"
                    style="line-height: 20px"
                  >
                    <!-- <div style="margin-bottom: 20px">
                      <div style="margin-bottom: 5px">
                        纠正预防措施原因分析：
                      </div>
                      <div>{{ workItem?.exceptionContentN1 || "" }}</div>
                    </div>

                    <div style="margin-bottom: 20px">
                      <div style="margin-bottom: 5px">
                        纠正预防措施实施以及完成时间：
                      </div>
                      <div>
                        完成时间：{{ formatDate(workItem?.n2?.planDate) }}
                      </div>
                      <div>{{ workItem?.n2?.exceptionContent || "" }}</div>
                    </div>

                    <div style="margin-bottom: 20px">
                      <div style="margin-bottom: 5px">纠正预防措施验证：</div>
                      <div>{{ workItem?.exceptionContentN3 || "" }}</div>
                    </div> -->

                    <div style="margin-bottom: 20px">
                      <div style="margin-bottom: 5px">
                        验证：(此栏由人力资源部部(企管办)/质量保证部/安全监管部填写)
                      </div>
                      <div>{{ workItem?.exceptionContent || "" }}</div>
                    </div>

                    <div style="display: flex">
                      <div style="flex: 1">
                        部门经理：{{ printData?.proposeManagerName || "" }}
                      </div>
                      <div style="flex: 1">
                        <div style="text-align: right">
                          经理审核时间：{{
                            formatDate(printData?.approvalTime)
                          }}
                        </div>
                      </div>
                    </div>
                  </div>
                </td>
              </tr>
            </table>

            <!-- 信息提示区域 -->
            <div style="display: flex; margin-top: 5px; line-height: 20px">
              <div style="flex: 1; padding: 0 10px; font-size: 14px">
                一式二联:①保留;②责任部门;人力资源部(企管办)负责批准体系审核和管理性的纠正和预防措施;质量保证部负责批街产品质量直接相关的纠正和预防措施，安监部负责批准EHS
                相关的纠正和预防措施。
              </div>
            </div>
          </div>
          <!-- </div> -->
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="startPrint">打印</el-button>
          <el-button type="primary" @click="PDFprit">PDF</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
// import {
//   mock,
//   templateType,
//   q8dd2Object,
//   calculateDefectRate,
//   isFirstInGroup,
//   getRowspan,
//   isFirstInGroupD8,
//   getRowspanD8,
//   getGrossScoreD8,
// } from "../index";
const dictionaryStore = useDictStoreHook();
import printJS from "print-js";

defineOptions({
  name: "Q8dqualityWorkorderPDFS",
  inheritAttrs: false,
});

const emit = defineEmits(["change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  id: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

watch(
  () => props.data,
  (newVal: any) => {
    if (newVal?.id) {
      getDetail();
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
}

const loading = ref(false);

// 时间转换
function formatDate(dateString: string | number | Date) {
  if (dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1
    const day = String(date.getDate()).padStart(2, "0");
    return `${year}年${month}月${day}日`;
  } else {
    return `   年  月  日`;
  }
}

import html2pdf from "../../q8dqualichecklist/components/PDF";

function PDFprit() {
  const table = document.getElementById("table");
  // html2pdf(table, {
  //   background: "#fff",
  //   minimumUnit: "tr",
  //   orientation: "l",
  // });
  html2pdf("table", "对账单", new Date());
}

// 打印数据
const printData = ref<any>();

const getDetail = async () => {
  loading.value = true;
  console.log("props.id", props.data.id);
  await request({
    url: `/qms/q8dqualityproblem/get/${props.data.id}`,
    method: "get",
    data: {},
  })
    .then((res) => {
      if (res.data != null) {
        printData.value = res.data;
        loading.value = false;
      } else {
        loading.value = false;
      }
    })
    .finally(() => {
      loading.value = false;
    });

  // setTimeout(() => {
  //   printData.value = mock;
  //   loading.value = false;
  // }, 500);
};

// 开始打印
function startPrint() {
  // 开始打印
  setTimeout(() => {
    printJS({
      printable: "printBox", // 打印内容的容器 id
      type: "html", // 打印类型
      imageStyle: "width:100%;margin-bottom:20px;",
      scanStyles: false,
      style: `
      @media print {
        @page {
          margin: 8mm 5mm;
        }
        body {
          margin: 0;
        }
        .page-break {
          page-break-before: always;
        }
        .dashed-border {
          width: 100%;
          border-collapse: collapse; /* 使边框合并为单一边框 */
          border: 1px solid #333;
        }

        .dashed-border td,
        .dashed-border th {
          font-size: 14px;
          border: 1px solid #333;
          min-height: 30px;
          padding: 5px 7px;
          overflow-wrap: anywhere;
          line-height: 24px;
          word-break: break-all;
        }

        tr {
          page-break-inside: avoid;
        }

        .bold td {
          font-weight: 600;
        }
      }
    `,
    });
  }, 1000);
}
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>

<style lang="scss" scoped>
.app-container {
  height: inherit;
  overflow: scroll;
  padding: 0;
}

:deep(.printDialog .el-dialog__body) {
  padding: 10px !important;
  height: calc(100vh - 220px);
  overflow: scroll;
}

.dashed-border {
  width: 100%;
  border-collapse: collapse; /* 使边框合并为单一边框 */
  border: 1px solid #606266;
}

.dashed-border td,
.dashed-border th {
  font-size: 14px;
  border: 1px solid #606266;
  min-height: 30px;
  padding: 5px 7px;
  overflow-wrap: anywhere;
  line-height: 24px;
  word-break: break-all;
}

tr {
  page-break-inside: avoid;
}

.bold td {
  font-weight: 600;
}
</style>
